package com.mojian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mojian.dto.user.SysUserPlatformBatchDto;
import com.mojian.dto.user.SysUserPlatformDto;
import com.mojian.entity.SysUserPlatform;
import com.mojian.exception.ServiceException;
import com.mojian.mapper.SysUserPlatformMapper;
import com.mojian.service.SysUserPlatformService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yuzhuo
 * @date: 2025/6/6
 * @description: 用户社交平台服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserPlatformServiceImpl extends ServiceImpl<SysUserPlatformMapper, SysUserPlatform> implements SysUserPlatformService {

    private final SysUserPlatformMapper sysUserPlatformMapper;

    @Override
    public List<SysUserPlatform> getUserSocialMediaList(Long userId) {
        return sysUserPlatformMapper.selectList(
                new LambdaQueryWrapper<SysUserPlatform>()
                        .eq(SysUserPlatform::getUserId, userId)
                        .eq(SysUserPlatform::getStatus, 1)
                        .orderByDesc(SysUserPlatform::getCreateTime)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createUserSocialMedia(SysUserPlatformDto dto) {
        // 检查用户是否已存在相同平台类型的记录
        SysUserPlatform existingPlatform = sysUserPlatformMapper.selectOne(
                new LambdaQueryWrapper<SysUserPlatform>()
                        .eq(SysUserPlatform::getUserId, dto.getUserId())
                        .eq(SysUserPlatform::getPlatformType, dto.getPlatformType())
                        .eq(SysUserPlatform::getStatus, 1)
        );
        
        if (existingPlatform != null) {
            throw new ServiceException("该平台类型已存在，请勿重复添加");
        }

        SysUserPlatform platform = SysUserPlatform.builder()
                .userId(dto.getUserId())
                .platformType(dto.getPlatformType())
                .homeUrl(dto.getHomeUrl())
                .fansCount(dto.getFansCount() != null ? dto.getFansCount() : 0)
                .contentCount(0)
                .likeCount(0)
                .avgEngagement(BigDecimal.ZERO)
                .isVerified(0)
                .verificationType(dto.getVerificationType() != null ? dto.getVerificationType().toString() : null)
                .monetizationStatus(0)
                .adCooperation(0)
                .platformTags(dto.getPlatformTags())
                .status(1)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        return sysUserPlatformMapper.insert(platform) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserSocialMedia(SysUserPlatformDto dto) {
        if (dto.getId() == null) {
            throw new ServiceException("ID不能为空");
        }

        SysUserPlatform existingPlatform = sysUserPlatformMapper.selectById(dto.getId());
        if (existingPlatform == null) {
            throw new ServiceException("社交平台记录不存在");
        }

        // 检查是否修改了平台类型，如果修改了需要检查是否与其他记录冲突
        if (!existingPlatform.getPlatformType().equals(dto.getPlatformType())) {
            SysUserPlatform conflictPlatform = sysUserPlatformMapper.selectOne(
                    new LambdaQueryWrapper<SysUserPlatform>()
                            .eq(SysUserPlatform::getUserId, dto.getUserId())
                            .eq(SysUserPlatform::getPlatformType, dto.getPlatformType())
                            .eq(SysUserPlatform::getStatus, 1)
                            .ne(SysUserPlatform::getId, dto.getId())
            );
            
            if (conflictPlatform != null) {
                throw new ServiceException("该平台类型已存在，请勿重复添加");
            }
        }

        SysUserPlatform platform = SysUserPlatform.builder()
                .id(dto.getId())
                .userId(dto.getUserId())
                .platformType(dto.getPlatformType())
                .homeUrl(dto.getHomeUrl())
                .fansCount(dto.getFansCount() != null ? dto.getFansCount() : existingPlatform.getFansCount())
                .contentCount(existingPlatform.getContentCount())
                .likeCount(existingPlatform.getLikeCount())
                .avgEngagement(existingPlatform.getAvgEngagement())
                .isVerified(existingPlatform.getIsVerified())
                .verificationType(dto.getVerificationType() != null ? dto.getVerificationType().toString() : existingPlatform.getVerificationType())
                .lastUpdate(existingPlatform.getLastUpdate())
                .platformLevel(existingPlatform.getPlatformLevel())
                .monetizationStatus(existingPlatform.getMonetizationStatus())
                .adCooperation(existingPlatform.getAdCooperation())
                .platformTags(dto.getPlatformTags())
                .createTime(existingPlatform.getCreateTime())
                .updateTime(LocalDateTime.now())
                .status(existingPlatform.getStatus())
                .build();

        return sysUserPlatformMapper.updateById(platform) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteUserSocialMedia(Long id) {
        SysUserPlatform platform = sysUserPlatformMapper.selectById(id);
        if (platform == null) {
            throw new ServiceException("社交平台记录不存在");
        }

        // 软删除：将状态设置为0
        SysUserPlatform updatedPlatform = platform.toBuilder()
                .status(0)
                .updateTime(LocalDateTime.now())
                .build();
        
        return sysUserPlatformMapper.updateById(updatedPlatform) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchSaveUserSocialMedia(SysUserPlatformBatchDto dto) {
        Long userId = dto.getUserId();
        List<SysUserPlatformDto> socialMediaList = dto.getSocialMediaList();

        // 先删除该用户所有现有的社交平台记录（软删除）
        List<SysUserPlatform> existingPlatforms = sysUserPlatformMapper.selectList(
                new LambdaQueryWrapper<SysUserPlatform>()
                        .eq(SysUserPlatform::getUserId, userId)
                        .eq(SysUserPlatform::getStatus, 1)
        );

        for (SysUserPlatform platform : existingPlatforms) {
            SysUserPlatform updatedPlatform = platform.toBuilder()
                    .status(0)
                    .updateTime(LocalDateTime.now())
                    .build();
            sysUserPlatformMapper.updateById(updatedPlatform);
        }

        // 批量插入新的社交平台记录
        List<SysUserPlatform> newPlatforms = new ArrayList<>();
        for (SysUserPlatformDto socialMediaDto : socialMediaList) {
            SysUserPlatform platform = SysUserPlatform.builder()
                    .userId(userId)
                    .platformType(socialMediaDto.getPlatformType())
                    .homeUrl(socialMediaDto.getHomeUrl())
                    .fansCount(socialMediaDto.getFansCount() != null ? socialMediaDto.getFansCount() : 0)
                    .contentCount(0)
                    .likeCount(0)
                    .avgEngagement(BigDecimal.ZERO)
                    .isVerified(0)
                    .verificationType(socialMediaDto.getVerificationType() != null ? socialMediaDto.getVerificationType().toString() : null)
                    .monetizationStatus(0)
                    .adCooperation(0)
                    .platformTags(socialMediaDto.getPlatformTags())
                    .status(1)
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .build();
            newPlatforms.add(platform);
        }

        return saveBatch(newPlatforms);
    }
} 